import random

from alipay import AliPay
from django import http
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render
from django.utils import timezone
from django.views import View
from django_redis import get_redis_connection

from material_hot import settings


class PaymentView(LoginRequiredMixin, View):
    """订单支付功能"""

    def get(self, request):
        # 查询要支付的订单
        user = request.user

        # 创建支付宝支付对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_path=settings.APP_PRIVATE_KEY_PATH,
            alipay_public_key_path=settings.ALIPAY_PUBLIC_KEY_PATH,
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )

        # 生成登录支付宝连接
        order_string = alipay.api_alipay_trade_page_pay(
            # out_trade_no=random.sample(range(0, 1000000000), 1000000000),
            out_trade_no= timezone.localtime().strftime('%Y%m%d%H%M%S') ,
            total_amount=str('112'),
            subject="美多商城%s" % '订单',
            return_url=settings.ALIPAY_RETURN_URL,
        )

        # 响应登录支付宝连接
        # 真实环境电脑网站支付网关：https://openapi.alipay.com/gateway.do? + order_string
        # 沙箱环境电脑网站支付网关：https://openapi.alipaydev.com/gateway.do? + order_string
        alipay_url = settings.ALIPAY_URL + "?" + order_string
        # alipay_url = settings.ALIPAY_URL
        # return http.JsonResponse({'code': 'OK', 'errmsg': 'OK', 'alipay_url': alipay_url})
        # return http.JsonResponse({'code': 'OK', 'errmsg': 'OK', 'alipay_url': alipay_url})
        return http.HttpResponseRedirect(alipay_url)


class PaymentStatusView(View):
    """订单支付功能"""

    def get(self, request):
        # 查询要支付的订单
        user = request.user
        redis_conn = get_redis_connection('carts')
        pl = redis_conn.pipeline()
        # 删除键，就等价于删除了整条记录
        pl.flushall()
        pl.execute()

        # 删除结束后，没有响应的数据，只需要响应状态码即可
        return http.JsonResponse({'code': 'OK', 'errmsg': '删除购物车成功'})
